<?php
class Response{
	protected $xml, $myDom, $error, $values, $tags;
	
	function Response($xml){
		if(strpos($xml, '<HTML>') !== FALSE) $xml = str_replace('<HTML>', '', $xml);
		if(strpos($xml, '<BODY>') !== FALSE) $xml = str_replace('<BODY>', '', $xml);
		$this->xml = $xml;
		//echo $xml;
		$this->parseXml();
		//var_dump($this->values);
		//var_dump($this->tags);	
	}
	
	function parseXml(){
		//var_dump($this->xml);
		$xml_parser = xml_parser_create();
		xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, 0);
    	xml_parser_set_option($xml_parser, XML_OPTION_SKIP_WHITE, 1);
		if(!xml_parse_into_struct($xml_parser, $this->xml, $this->values, $this->tags)){
			$this->error = new Error('XML Parsing Died at line: ' . xml_get_current_line_number($xml_parser));
		}
		xml_parser_free($xml_parser); 	
	}
	
	function getTagValue($tag_name){
		$tag_indexes = $this->tags[$tag_name];
		$i = 0;
		if($this->values[$tag_indexes[$i]]['type'] == 'complete'){
			$out = $this->values[$tag_indexes[$i]]['value'];
		}
		else{
			$out = $this->composeTag($tag_indexes[$i]);
		}
		return $out;
	}
	
	function getAllByTagName($tag_name){
		$out = array();
		$tag_indexes = $this->tags[$tag_name];
		//This contains indexes of both opening and closing tags... so we skip the closing tags
		for($i = 0;$i < count($tag_indexes); $i = $i + 2){
			if($this->values[$tag_indexes[$i]]['type'] == 'complete'){
				$out[] = $this->values[$tag_indexes[$i]]['value'];
			}
			else{
				$out[] = $this->composeTag($tag_indexes[$i]);
			}
		}
		return $out;
	}
	
	function composeTag($tag_index){
		$tag = array();
		$cur_index = $tag_index;
		while(true){
			$cur_index++;
			//var_dump($this->values[$cur_index]);
			if($this->values[$cur_index]['type'] == 'close') break;
			$tag[$this->values[$cur_index]['tag']] = $this->values[$cur_index]['value'];
			flush();
			ob_flush();
		}
		return $tag;
	}
	
	function getErrorCode(){
		return $this->getTagValue('ErrorCode');
	}
	
	function getErrorText(){
		return $this->getTagValue('ErrorText');		
	}
}
?>